package com.neborosoft.lib.threading;

import com.neborosoft.lib.utilities.Utilities;

/**
 * Created with IntelliJ IDEA.
 * User: CM
 * Date: 29.09.12
 * Time: 5:44
 * To change this template use File | Settings | File Templates.
 */
public class AsyncTimer{
    private Runnable action;
    private volatile boolean paused = false, stopped = true;
    public AsyncTimer(Runnable action){
        setAction(action);
    }
    public void start(final long delay){
        if(!stopped)
        {
            paused = false;
            return;
        }
        stopped = paused = false;
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run(){
                while (!stopped){
                    try{
                        Thread.sleep(delay);
                        if(!paused){
                            action.run();
                        }
                    }
                    catch (InterruptedException e){
                        Utilities.logException(e);
                    }
                }
            }
        });
        thread.start();
    }
    public boolean isStopped(){
        return stopped;
    }
    public boolean isPaused(){
        return paused;
    }
    public void pause(){
        paused = true;
    }
    public void stop(){
        stopped = true;
    }
    public void setAction(Runnable action){
        this.action = action;
    }
}
